<template>
  <el-dialog
    class="ideskForm"
    title="创建工单"
    :visible.sync="visible"
    v-if="visible"
    :close-on-click-modal="false"
    destroy-on-close
    @close="closed"
  >

    <FormCreate v-if="visible" :rule="totalRules" v-model="tableForm" @file="fileChange" :option="options"/>
    <ElButton type="primary" plain @click="submit">提交</ElButton>
    <ElButton aligen="center" plain @click="reset">重置</ElButton>
  </el-dialog>
</template>

<script>
  import request from '@/utils/request'
  import { maker } from '@form-create/element-ui'
  import { getFormData ,startProcess} from '@/api/flowable'
  export default {
    components: {maker},
    data() {
      return {
        src: null,
        visible: false,
        iframeHeight: '',
        tableForm: {},
        tableFields: [],
        key:'',
        options: {
          submitBtn: false,
          resetBtn: false,
          onSubmit: (formData) => {
            alert(JSON.stringify(formData))
          },
          global: {
            '*': {
              props: {
                disabled: false
              },
              col: {
                span: 12
              }
            },
            upload: {
              props: {
                onError: function (r) {
                  alert('上传失败');
                }
              }
            }
          }
        },
        rule: [
        ],
        extendsRules: [],
        totalRules: [],
        processDefinitionId: '',
        formId: '',
        name: '',
        orgCode: '',
        fileList: [],
        attachments:[],
        attachmentsValue:[],
        sceneCode: '',
        processType: ''
      }
    },
    created() {
      this.$nextTick(() => {
        const deviceHeight = document.documentElement.clientHeight
        this.iframeHeight = deviceHeight + 'px'

      })
    },
    methods: {
      async init(val) {
        this.rule = []
        this.totalRules = this.rule
        this.visible = true
        this.key = val.key
        this.formId = val.formId
        this.name = val.name
        this.sceneCode = val.sceneCode
        this.processType = val.processType
        this.processDefinitionId = val.id

        const {code, data} = await getFormData(val.id)
        if(code == "200") {
          let json = JSON.parse(data.modelEditorJson)
          this.tableFields = json.fields
          for(let item of this.tableFields) {
            if (item.type == 'upload') {
              this.extendsRules.push({
                type: 'upload',
                field: item.id,
                title: item.name,
                value: this.attachmentsValue,
                props: {
                  "type": "select",
                  "action": '',
                  "listType": 'text',
                  'showFileList': true,
                  'autoUpload': false,
                  'headers': {'Authorization':getToken(),'user': getUserName()},
                  "name": "file",
                  'httpRequest': (content) =>{
                    console.log("手动提交文件")
                  },
                  "multiple": true,
                  "onSuccess":  (res, file,fileList) => {
                    let content = res.content;
                    this.attachmentsValue.push(content.attName)
                  },
                  "onChange": (file,fileList) => {
                    // this.attachments = fileList
                    this.length=document.querySelector("input[type=file]").files.length;
                    if(this.length>0){
                      Array.from(document.querySelector("input[type=file]").files).forEach(file=>{
                        if(this.attachments.indexOf(file) == -1){
                          this.attachments.push(file);
                        }
                      })
                    }
                    return false;
                  },
                  "onRemove": function (file,fileList) {
                    this.attachments = fileList
                  },
                },
                col: {
                  span: 24
                }
              })
            } else if (item.type == 'multi-line-text') {
              this.extendsRules.push({
                type: 'input',
                field: item.id,
                title: item.name,
                props: {
                  "type": "textarea",
                  // "placeholder": "请输入商品名称",
                  "rows": 5
                },
                col: {
                  span: 24
                }
              })
            } else if (item.type == 'radio-buttons') {
              this.extendsRules.push({
                type: 'checkbox',
                field: item.id,
                title: item.name,
                value: ["1", "2", "3"],
                options: [
                  {value: "1", label: "好用", disabled: true},
                  {value: "2", label: "方便", disabled: false},
                  {value: "3", label: "实用", disabled: false},
                  {value: "4", label: "有效", disabled: false},
                ]
              })
            }else if(item.type =="dropdown") {
              // request({
              //   url: `/business/dict/item/select/${item.placeholder}`,
              //   params: {
              //     multiple: this.multiple == null ? null : 1
              //   }
              // }).then((response) => {
              //   this.options = response.data.content
              // })
              this.extendsRules.push({
                type: "select",
                field: item.id,
                title: item.name,
                // value: "104",
                col: {
                  span: 12
                },
                props: {
                  multiple: false
                },
                options: item.params.options
              })
            } else if(item.type =="date") {
              this.extendsRules.push({
                type: "DatePicker",
                field: item.id,
                title: item.name,
                value: [],
                props: {
                  "type": "datetime",
                  "format": "yyyy-MM-dd HH:mm:ss",
                  "placeholder":"请选择活动日期",
                }
              })
            }else {
              this.extendsRules.push({
                type: 'input',
                field: item.id,
                title: item.name
              })
            }
          }
            this.totalRules = this.rule.concat(this.extendsRules)
        }
      },
      async submitData(formData) {
        const {code} = await startProcess(this.processDefinitionId,formData)
        this.visible= false
      },
      submit() {
        this.tableForm.submit((formData1, $f)=>{
          let formData = new FormData();
          console.log(this.attachments)
          if(this.attachments.length>0){
            this.attachments.forEach(file=> {
              formData.append("files", file);
            });

            //	走接口
            console.log(formData.getAll("files"));
            let _url = "*****";//上传文件接口地址
            request({
              url: '/user/fast/demo/upload/fileMultiples',
              method: 'post',
              data:formData,
            }).then((res) => {
              console.log(res)
              //此处重置文件中间存储变量是为了相同文件能够重复传递
              if (res.data.code == '200'){
                // this.$message.success(`成功`);
                let formData = this.tableForm.form
                formData["attachment"] = res.data.content
                this.submitData(formData)
              } else {
                this.$message.success(`失败`);
              }
            }, (err) =>{
              this.attachments=[];
              this.$message.success(`失败`);
            })
          } else {
              this.submitData(formData1)
          }
        })
      },
      reset(){
        this.tableForm.resetFields();
      },
      closed(){
        this.visible = false
        this.extendsRules = []
        this.totalRules = []
      },
      fileChange(){
        console.log("触发监听事件")
      },
      //上传文件用到的两个方法

      change(){
        //判断上传文件数量
        this.length=document.querySelector("input[type=file]").files.length;
        if(this.length>0){
          Array.from(document.querySelector("input[type=file]").files).forEach(file=>{
            if(this.fileList.indexOf(file) == -1){
              this.fileList.push(file);
            }
          })
        }
        return false;
      }
    }
  }
</script>

<style>
  .ideskForm textarea {
    width: 100%;
  }
  .ideskForm .el-select {
    width: 100%
  }
  .ideskForm .el-date-editor {
    width: 100%;
  }
</style>
